<?php


namespace app\api\controller\xilumarket;


use addons\xilumarket\controller\WeixinMini;
use app\common\controller\Api;
use app\common\model\xilumarket\Aftersale AS AftersaleModel;
use think\Db;
use think\Exception;
use function fast\array_get;

class Aftersale extends Api
{
    protected $noNeedRight = ['*'];


    /**
     * 售后列表
     */
    public function lists(){
        $params = $this->request->param('');
        $result = AftersaleModel::lists($params);
        $this->success('',$result);
    }

    /**
     * 申请售后
     */
    public function apply_aftersale(){

        $params = $this->request->param('');
        Db::startTrans();
        try {
            $result = AftersaleModel::add($params,$this->auth->getUser());
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('提交售后成功',$result);
    }
    /**
     * 同意申请-处理中
     */
    public function agree_apply($aftersale_id=NULL){
        if(!$aftersale_id){
            $this->error('售后参数错误');
        }
        $aftersale = AftersaleModel::get($aftersale_id);
        if(!$aftersale || !in_array($aftersale->state,[AftersaleModel::AFTERSALE_STATUS_APPLY])){
            $this->error('状态不可设置');
        }
        $order = \app\common\model\xilumarket\Order::where('id', $aftersale->order_id)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        Db::transaction(function () use ($aftersale,$order) {
            $aftersale->state = AftersaleModel::AFTERSALE_STATUS_NOOPER;    // 同意申请
            $aftersale->agreetime = time();
            $aftersale->save();

            // 增加售后单变动记录
            \app\common\model\xilumarket\AftersaleLog::operate_add($order, $aftersale, $this->auth->getUser(), 'user', [
                'title' => '卖家同意退款申请',
                'description' => '售后申请已通过审核，等待提交物流信息',
                'images' => []
            ]);
        });
        $this->success('保存成功');
    }

    /**
     * 拒接申请
     */
    public function refuse(){
        $params = $this->request->post('');
        $aftersale_id = array_get($params,'aftersale_id');
        $aftersale = $aftersale_id?AftersaleModel::get($aftersale_id):null;
        if(!$aftersale){
            $this->error('售后信息未找到');
        }
        if(!$aftersale || !in_array($aftersale->state,[
                AftersaleModel::AFTERSALE_STATUS_APPLY,
                AftersaleModel::AFTERSALE_STATUS_FREIGHT,
            ])){
            $this->error('状态不可设置');
        }
        if(!$refuse_content = array_get($params,'refuse_content')){
            $this->error('请输入拒绝理由');
        }
        //修改数据
        $order = \app\common\model\xilumarket\Order::where('id', $aftersale->order_id)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        Db::transaction(function () use ($aftersale,$order,$refuse_content) {
            $aftersale->state = AftersaleModel::AFTERSALE_STATUS_REFUSE;    // 拒绝申请
            $aftersale->refuse_content = $refuse_content;    // 拒绝申请
            $aftersale->agreetime = time();
            $aftersale->save();

            $order->refund_status = '3';
            $order->refund_time = time();
            $order->save();
            // 增加售后单变动记录
            \app\common\model\xilumarket\AftersaleLog::operate_add($order, $aftersale, $this->auth->getUser(), 'user', [
                'title' => '卖家拒绝售后申请',
                'description' => "拒绝理由：".$refuse_content,
                'images' => []
            ]);
        });
        $this->success('保存成功');
    }

    /**
     * 同意退款
     */
    public function refund(){
        $aftersale_id = $this->request->post('aftersale_id');
        $aftersale = $aftersale_id?AftersaleModel::withTrashed()->where('id', $aftersale_id)->find() :null;
        if (!$aftersale || !in_array($aftersale->state,[AftersaleModel::AFTERSALE_STATUS_APPLY,AftersaleModel::AFTERSALE_STATUS_FREIGHT])) {
            $this->error('售后单不存在或在不可退款状态');
        }
        $order = \app\common\model\xilumarket\Order::where('id', $aftersale->order_id)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        #申请中的退款金额
        $refund_money = $aftersale->price;
        Db::transaction(function () use ($aftersale, $order, $refund_money) {

            $aftersale->state = AftersaleModel::AFTERSALE_STATUS_REFUND;    // 同意退款
            $aftersale->refundtime = time();
            $aftersale->refund_price = $refund_money;     // 退款金额
            $aftersale->save();

            // 增加售后单变动记录
            \app\common\model\xilumarket\AftersaleLog::operate_add($order, $aftersale, $this->auth->getUser(), 'user', [
                'title' => '卖家同意退款',
                'description' => '售后订单已退款',
                'images' => []
            ]);
            $order->refund_status = 2;
            $order->save();

            #第三方退款走这里
            $weixin = new WeixinMini();
            $res = $weixin->refund($aftersale->id,$refund_money,'aftersale');
            if(!$res['status']){
                $this->error($res['msg']);
            }

        });
        $this->success('操作成功');
    }

    /**
     * 提交物流
     */
    public function apply_express()
    {
        $params = $this->request->post('');
        try {
            $result = AftersaleModel::express($params,$this->auth->getUser());
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('提交物流成功',$result);
    }

}